package com.mandao.oneplat.boot.handler;

import com.mandao.oneplat.boot.OnePlatConfig;
import com.mandao.oneplat.boot.context.OneContext;
import com.mandao.oneplat.boot.context.OneRequest;
import com.mandao.oneplat.boot.mvc.control.OneControlUriResult;
import com.mandao.oneplat.boot.mvc.control.OneControllerDispacher;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by sunson on 2017/3/21.
 */
public class OneServerControlHandler extends ChannelInboundHandlerAdapter {

    private Logger logger = LoggerFactory.getLogger(getClass());

    private OnePlatConfig oneOption;
    protected OneControllerDispacher oneControllerDispacher;

    public OneServerControlHandler(OneControllerDispacher oneControllerDispacher, OnePlatConfig oneOption) {
        this.oneOption = oneOption;
        this.oneControllerDispacher = oneControllerDispacher;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        if (msg instanceof OneContext) {
            OneContext oneContext = (OneContext) msg;
            OneRequest oneRequest = oneContext.getOneRequest();
            // 路径参数解析
            OneControlUriResult oneUriResult = oneControllerDispacher.resovleUri(oneRequest.getUri());
            // 解析PathVariable的参数
            oneRequest.setPathUri(oneUriResult.getPath());
            oneRequest.addParams(oneUriResult.getParams());
            logger.info("来源请求：{}", oneRequest.toString());
            oneContext.setOneView(oneControllerDispacher.callController(oneUriResult.getPath(), oneContext));
            ctx.write(oneContext);
        }
    }
}
